//
//  MeatMarketsViewController.m
//  PigMarket
//
//  Created by 张敬 on 2019/7/15.
//  Copyright © 2019年 pigmarket.oc. All rights reserved.
//

#import "MeatBuyViewController.h"

#import "MeatBuySectionView.h"

#import "MeatMarketsTableViewCell.h"
#import "MeatMarketCrossTableViewCell.h"
#import "MeatMarketsBannerTableViewCell.h"

#import "MeatMarketApi.h"
#import "MeatMainScreeningBox.h"

#import "MeatShopListViewController.h"
#import "MeatCartViewController.h"
#import "MeatSearchShopViewController.h"
#import "MeatMapViewController.h"
#import "MeatPriceViewController.h"


@interface MeatBuyViewController ()<UIScrollViewDelegate>

@property (nonatomic, assign) BOOL isSwitchShopType;

@property (nonatomic, strong) MeatMarketApi *meatApi;
@property (nonatomic, strong) BuyMeatadvertiseListModel *bannerModel;
@property (nonatomic, strong) BuyMeatPageModel *listModel;
@property (nonatomic, strong) BuyMeatPartListModel *menuListModel;
@property (nonatomic, strong) PigVarietyList *pigTypeList;

@property (nonatomic, strong) MeatPriceRangeModel *priceModel;


@property (nonatomic, strong) UIView *customView;
@property (nonatomic, strong) UIImageView *customIcon;

@property (nonatomic, strong) UIView *priceView;
@property (nonatomic, strong) UIImageView *priceIcon;

@property (nonatomic, strong) NSArray <BuyMeatadvertiseListModel *>*aimsArray;

@property (nonatomic, assign) BOOL isShow;

@end

@implementation MeatBuyViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self initData];
}

#pragma mark - init method

- (void)setupUI{
    
    [self initView];
}


- (void)initView {
    
    self.isSwitchShopType = NO;
    self.baseNavView.hidden = YES;
    self.isShow = YES;
    self.isRefresh = YES;
    [self.view addSubview:self.customView];
    [self.view addSubview:self.priceView];
}


- (void)setupLayout{
    
    self.reloadBtn.mj_y -= 100;
    self.reloadLab.mj_y -= 100;
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.mas_equalTo(0);
        make.bottom.mas_equalTo(0);
    }];
}

- (void)initData {
    
    [self requestBuyMeatAdvertiseData];
    [self requestBuyMeatPartDataWithType:@1];
    NSNumber *page = [NSNumber numberWithInteger:self.page];
    MeatShopListParam *params = [MeatShopListParam new];
    params.page = page;
    params.limit = @10;
    params.tribeId = @2;
    [self requestShopListByParam:params];
    [self boxData];

}

- (void)boxData{
    [self requestPigVariety];
}


#pragma mark - networking method
//肉市-卖肉-广告
- (void)requestBuyMeatAdvertiseData {
    
    @weakify(self);
    [[self.meatApi getBuyMeatAdvertiseListData] subscribeNext:^(BuyMeatadvertiseListModel * _Nullable bannerModel) {
        
        @strongify(self);
        self.bannerModel = [[BuyMeatadvertiseListModel alloc] init];
        self.bannerModel = bannerModel;
    }];
}

//肉市-卖肉-部位信息
- (void)requestBuyMeatPartDataWithType:(NSNumber *)type{
    
    @weakify(self);
    [[self.meatApi getBuyMeatPartListDataWithType:type] subscribeNext:^(BuyMeatPartListModel * _Nullable menuListModel) {
        
        @strongify(self);
        self.menuListModel = [[BuyMeatPartListModel alloc] init];
        self.menuListModel = menuListModel;
    }];
}

//获取价格区间列表
- (void)requestPriceRange{
    
    @weakify(self);
    [[self.meatApi getMeatShopPriceList] subscribeNext:^(MeatPriceRangeModel * _Nullable model) {
        
        @strongify(self);
        self.priceModel = model;
    }];
}

//品种请求
- (void)requestPigVariety {
    @weakify(self);
    [[[PigMarketApi sharedInstance] getPigVariety] subscribeNext:^(PigVarietyList * _Nullable pigVarietyList) {
        @strongify(self);
        self.pigTypeList = pigVarietyList;
    }];
}


//肉市-卖肉-店铺信息
- (void)requestShopListByParam:(MeatShopListParam *)params{

    @weakify(self);
    [[self.meatApi getShoppingListByParams:params] subscribeNext:^(BuyMeatListModel * _Nullable listModel) {
        @strongify(self);
        
        if (self.isRefresh) {
            [self endRefresh];
        }
        
        {
            BuyMeatPageModel *pageModel = listModel.page;
            [pageModel.list enumerateObjectsUsingBlock:^(BuyMeatModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                
                NSNumber *shopId = obj.shopId;
                [[self.meatApi getBuyMeatPigTypeListByShopId:shopId] subscribeNext:^(PigTypeListModel * _Nullable model) {
                    
                    obj.saleType = model.arrearsIf;
                }];
            }];
        }
        
        self.listModel = listModel.page;
        self.isShow = [listModel.shoppingCartCount intValue] == NO ?YES :NO;
        
        if ([self.listModel.totalCount intValue] < [self.listModel.pageSize intValue] ) {
            [self endLoadMoreMoData];
        }else if ([self.listModel.totalCount intValue] == [self.listModel.pageSize intValue]){
            
            if ([self.listModel.currPage intValue] >= [self.listModel.totalCount intValue]) {
                [self endLoadMoreMoData];
            }else{
                [self endLoadMore];
            }
        }
        
        if (self.listModel.list.count >0) {
            self.tableView.hidden = NO;
            [self.tableView reloadData];
        }else{
            [self loadNoData];
        }
        
    }error:^(NSError * _Nullable error) {
        @strongify(self);
        [self loadErrorData];
    }];
}


//下拉刷新
- (void)refresh
{
    [super refresh];
    [self resetData];
    [self initData];
    [self postNotifications];
}

//上拉加载更多
- (void)loadMore
{
    [super loadMore];
    NSNumber *page = [NSNumber numberWithInteger:self.page];
    MeatShopListParam *params = [MeatShopListParam new];
    params.page = page;
    params.limit = @10;
    params.tribeId = @2;
    [self requestShopListByParam:params];
}


#pragma mark - private method

- (void)postNotifications{
    
    [kNotificationCenter postNotificationName:kMeatMarketMainHeaderNotification object:nil];
}

- (void)scrollTableViewTop{
    kWeakSelf(self);
    NSIndexPath *ip = [NSIndexPath indexPathForRow:0 inSection:1];
    [weakself.tableView scrollToRowAtIndexPath:ip atScrollPosition:UITableViewScrollPositionTop animated:YES];
}

#pragma mark - tableview delegate/dataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    NSInteger num = self.listModel.list.count;
    NSInteger crossRow = num %2 == 0 ?num/2 :(num/2 +1);
    NSInteger rows = self.isSwitchShopType ?crossRow :num;
    return section == 0 ?1 :rows;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    if (section == 0) {
        return 0;
    }
    return self.listModel.list.count >0 ?37 :0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    MeatBuySectionView *sectionView = [[MeatBuySectionView alloc] init];
    sectionView.pigListModel = self.pigTypeList;
    sectionView.isShowRedView = self.isShow;
    sectionView.cross = self.isSwitchShopType;
    sectionView.partModel = self.menuListModel;

    
    //购物车Block
    @weakify(self);
    sectionView.dealJumpCartBlock = ^{
        @strongify(self);
        MeatCartViewController *vc = [[MeatCartViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    };
    
    //切换店铺样式BLock
    sectionView.dealSwitchShopStyleBlock = ^{
        @strongify(self);
        
        self.isSwitchShopType = !self.isSwitchShopType;
        
        [UIView transitionWithView: self.tableView
                          duration: 0.35f
                           options: UIViewAnimationOptionTransitionCrossDissolve
                        animations: ^(void)
         {
             [self.tableView reloadData];
         }
                        completion: ^(BOOL isFinished)
         {
         }];
    };
    
    //筛选条件Block
    sectionView.dealScreeningBlock = ^(UIButton *btn) {
        @strongify(self);
        [self scrollTableViewTop];
    };
    
    //okBlock
    sectionView.resetDataBlock = ^(MeatShopListParam *param) {
       @strongify(self);
        [self requestShopListByParam:param];
    };
    
    return self.listModel.list.count >0 ?sectionView :nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    CGFloat listHeight = self.isSwitchShopType? 277 : 140;
    CGFloat bannerHeight = self.menuListModel.position.count >5 ? 371 : 281;
    return indexPath.section == 0 ?bannerHeight : listHeight;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        MeatMarketsBannerTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MeatMarketsBannerTableViewCell"];
        cell.list = self.bannerModel.list;
        cell.pigPartsArray = self.menuListModel.position;
        cell.backgroundColor = mBackgroudColor;
        
#pragma mark -  //轮播图BLock
        @weakify(self);
        cell.dealBannerBlock = ^(NSInteger params) {
            @strongify(self);
            MeatMapViewController *vc = [[MeatMapViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        };
 
#pragma mark -  //猪部位ItemBlock
        cell.dealItemBlock = ^(NSInteger params) {
            @strongify(self);
            ////主键id
            BuyMeatPartModel *item = self.menuListModel.position[params];
            MeatSearchShopViewController *vc = [[MeatSearchShopViewController alloc] init];
            vc.pigPositionId = item.pigPositionId;
            [self.navigationController pushViewController:vc animated:YES];
        };
        
        return cell;
    }
    
  
    if (self.isSwitchShopType) {
        MeatMarketCrossTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MeatMarketCrossTableViewCell"];
        NSInteger num = indexPath.row *2;
        BuyMeatModel *model1 = self.listModel.list[num];
        BuyMeatModel *model2 = self.listModel.list[num +1];
        cell.meatModel1 = model1;
        cell.meatModel2 = model2;
        
        @weakify(self);
        cell.dealShopDetailBlock = ^(NSInteger params) {
            @strongify(self);
            BuyMeatModel *model  = nil;
            if (params == 1 ) {
                model = model1;
            }else{
                model = model2;
            }
            MeatShopListViewController *vc = [[MeatShopListViewController alloc] init];
            vc.shopId = model.shopId;
            [self.navigationController pushViewController:vc animated:YES];
        };
        
        return cell;
        
    }else{
        
        MeatMarketsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MeatmarketsTableViewCell"];
        if (indexPath.row <self.listModel.list.count) {
            BuyMeatModel *model = self.listModel.list[indexPath.row];
            cell.meatModel = model;
        }
        return cell;
    }
    
    return [UITableViewCell new];
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (!self.isSwitchShopType) {
        BuyMeatModel *model = self.listModel.list[indexPath.row];
        MeatShopListViewController *vc = [[MeatShopListViewController alloc] init];
        vc.shopId = model.shopId;
        vc.saleType = model.saleType;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

    
#pragma mark - getter and setter

- (MeatMarketApi *)meatApi{
    
    if(!_meatApi){
        _meatApi = [[MeatMarketApi alloc]init];
    }
    return _meatApi;
}


- (UIView *)customView{
    
    if (!_customView) {
        _customView = [[UIView alloc] init];
        _customView.size = CGSizeMake(80, 60);
        _customView.mj_y = 120;
        _customView.mj_x = KScreenWidth - 80;
        _customView.tag = 300;
        
        [_customView addSubview:self.customIcon];
        
        
        @weakify(self);
        _customView.tapBlock = ^{
            @strongify(self);
            
            if (self.customView.tag == 300) {
                self.customView.tag = -300;
                
                [self setAnimationByX:-40 transferX:-M_PI/4 transferY:0 isJump:YES layer:self.customIcon.layer];
            }else{
                
                self.customView.tag = 300;
                [self setAnimationByX:10 transferX:0 transferY:-M_PI/4 isJump:NO layer:self.customIcon.layer];
            }
        };
    }
    return _customView;
}


- (UIImageView *)customIcon{
    
    if (!_customIcon) {
        _customIcon = [UIImageView makeImageByImageName:@"meat_buy_customerservice" cornerRadius:0];
        _customIcon.size = CGSizeMake(60, 60);
        _customIcon.mj_x =  70 - _customIcon.width/2.0;
        _customIcon.mj_y = 0;
        CGAffineTransform at = CGAffineTransformMakeRotation(-M_PI/4);
        [_customIcon setTransform:at];
        
    }
    return _customIcon;
}


- (void)setAnimationByX:(CGFloat)x transferX:(CGFloat)from transferY:(CGFloat)to isJump:(BOOL)jump layer:(CALayer *)layer{
    
    CABasicAnimation *animation1 = [CABasicAnimation animationWithKeyPath:@"transform.translation.x"];
    animation1.toValue = @(x);
    
    CABasicAnimation *animation2 = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    animation2.fromValue = [NSNumber numberWithFloat: from];
    animation2.toValue = [NSNumber numberWithFloat:to];
    
    if (jump) {
    
        CAAnimationGroup *group = [CAAnimationGroup animation];
        group.duration = 0.8;
        group.repeatCount = 1;
        group.autoreverses = NO; //默认就是NO，设置成Yes之后下面fillMode就不起作用了
        group.fillMode = kCAFillModeForwards;
        group.removedOnCompletion = NO;
        group.animations = [NSArray arrayWithObjects:animation1, animation2, nil];
        [layer addAnimation:group forKey:@"group"];
    }else{
        
        CAAnimationGroup *group = [CAAnimationGroup animation];
        group.duration = 0.4;
        group.repeatCount = 1;
        group.autoreverses = NO; //默认就是NO，设置成Yes之后下面fillMode就不起作用了
        group.fillMode = kCAFillModeForwards;
        group.removedOnCompletion = NO;
        group.animations = [NSArray arrayWithObjects:animation1, animation2, nil];
        [layer addAnimation:group forKey:@"group"];
    }
    
    if (jump) {
        
        CAKeyframeAnimation *animation = [CABasicAnimation makeGravityJumpAnimation];
        [layer addAnimation:animation forKey:nil];
    }
}


- (UIView *)priceView{
    
    if (!_priceView) {
        _priceView = [[UIView alloc] init];
        _priceView.size = CGSizeMake(80, 60);
        _priceView.mj_y = 280;
        _priceView.mj_x = KScreenWidth - 80;
        _priceView.tag = 400;
        [_priceView addSubview:self.priceIcon];
        
        @weakify(self);
        _priceView.tapBlock = ^{
            @strongify(self);
            
            if (self.priceView.tag == 400) {
                self.priceView.tag = -400;
                [self setAnimationByX:-40 transferX:-M_PI/4 transferY:0 isJump:YES layer:self.priceIcon.layer];
            }else{
                self.priceView.tag = 400;
                [self setAnimationByX:10 transferX:0 transferY:-M_PI/4 isJump:NO layer:self.priceIcon.layer];
                
                MeatPriceViewController *vc = [[MeatPriceViewController alloc] init];
                [self.navigationController pushViewController:vc animated:YES];
            }
        };
    }
    
    return _priceView;
}


- (UIImageView *)priceIcon{
    
    if (!_priceIcon) {
        _priceIcon = [UIImageView new];
        _priceIcon.image = [UIImage imageNamed:@"meat_buy_orange"];
        _priceIcon.size = CGSizeMake(60, 60);
        _priceIcon.mj_x = 70 - _priceIcon.width /2.0;
        _priceIcon.mj_y = 0;
        
        CGAffineTransform at = CGAffineTransformMakeRotation(-M_PI/4);
        [_priceIcon setTransform:at];
    }
    return _priceIcon;
}

- (BuyMeatPageModel *)listModel
{
    if (!_listModel) {
        _listModel = [[BuyMeatPageModel alloc] init];
    }
    return _listModel;
}

- (MeatPriceRangeModel *)priceModel{
    
    if (!_priceModel) {
        _priceModel = [[MeatPriceRangeModel alloc] init];
    }
    return _priceModel;
}

- (PigVarietyList *)pigTypeList{
    
    if (!_pigTypeList) {
        _pigTypeList = [PigVarietyList new];
    }
    return _pigTypeList;
}

#pragma mark - override methods

- (void)registerTableViewCell{
    
    [self.tableView registerClass:[MeatMarketsBannerTableViewCell class] forCellReuseIdentifier:@"MeatMarketsBannerTableViewCell"];
    [self.tableView registerClass:[MeatMarketsTableViewCell class] forCellReuseIdentifier:@"MeatmarketsTableViewCell"];
    [self.tableView registerClass:[MeatMarketCrossTableViewCell class] forCellReuseIdentifier:@"MeatMarketCrossTableViewCell"];
}

- (void)loadErrorData
{
    [super loadErrorData];
    self.customView.hidden = YES;
    self.priceView.hidden = YES;
}

- (void)loadNoData
{
    [super loadNoData];
    self.customView.hidden = YES;
    self.priceView.hidden = YES;
}


- (void)endLoadMore{
    [super endLoadMore];
    self.customView.hidden = NO;
    self.priceView.hidden = NO;

}

- (void)endRefresh{
    [super endRefresh];
    self.customView.hidden = NO;
    self.priceView.hidden = NO;

}

- (void)endLoadMoreMoData
{
    [super endLoadMoreMoData];
    self.customView.hidden = NO;
    self.priceView.hidden = NO;
}

- (void)dealloc{
    [self showHudWithMsg:@"我解放了"];
}

@end
